import { ObjTypes } from "../appTypes";
const bcrypt = require('bcrypt');
/**
 * 获取随机数
 * @returns 随机数
 */
export const getRandomNumber = ()=>{
  let r = Math.random()*10;
  let time = (new Date()).getTime();
  let res = Math.round(time*r);
  return res;
}

/**
 * 动态生成对象
 * @param obj 对象
 * @returns 对象
 */

export const generateObject = (obj:ObjTypes):ObjTypes=>{
  let returnObj:ObjTypes = {};
  for(let key in obj){
    if(obj[key] != undefined){
      returnObj[key] = obj[key];
    }
  }
  return returnObj;
}


export const generatePwd = (pwd:string):string=>{
  const saltRounds = 8;
  const salt = bcrypt.genSaltSync(saltRounds);
  const hash = bcrypt.hashSync(pwd, salt);
  return hash;
}

export const parsingQueryString = (path:string):ObjTypes=>{
  let queryStr = path.split("?")[1];
  let queryArr = queryStr.split("&");

  let obj = {};

  for(let i=0;i<queryArr.length;i++){
    let item = queryArr[i];
    let itemArr = item.split("=");
    obj[itemArr[0]] = itemArr[1];
  }
  return obj;
}


export const getSocketMsg = (props:{code:number,msg:ObjTypes}):string=>{
  return JSON.stringify({
    msgID:props.code,
    ...props.msg
  });
}